import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import { MavenUtils } from '../mavenUtils';

/**
 * 表示Maven模块的树状节点
 */
class MavenModuleItem extends vscode.TreeItem {
    constructor(
        public readonly label: string,
        public readonly pomPath: string,
        public readonly collapsibleState: vscode.TreeItemCollapsibleState,
        public readonly children?: MavenModuleItem[]
    ) {
        super(label, collapsibleState);
        
        this.tooltip = `${label} (${pomPath})`;
        this.description = path.relative(vscode.workspace.rootPath || '', path.dirname(pomPath));
        
        // 为父模块和子模块设置不同的图标
        this.iconPath = collapsibleState === vscode.TreeItemCollapsibleState.None
            ? new vscode.ThemeIcon('file-code')
            : new vscode.ThemeIcon('package');
            
        // 添加上下文菜单
        this.contextValue = 'mavenModule';
    }
}

/**
 * Maven模块视图的数据提供者
 */
export class MavenModulesProvider implements vscode.TreeDataProvider<MavenModuleItem> {
    private _onDidChangeTreeData: vscode.EventEmitter<MavenModuleItem | undefined> = new vscode.EventEmitter<MavenModuleItem | undefined>();
    readonly onDidChangeTreeData: vscode.Event<MavenModuleItem | undefined> = this._onDidChangeTreeData.event;
    
    private mavenUtils: MavenUtils;
    
    constructor() {
        this.mavenUtils = new MavenUtils();
    }
    
    /**
     * 刷新树视图
     */
    public refresh(): void {
        this._onDidChangeTreeData.fire(undefined);
    }
    
    /**
     * 获取树视图项
     */
    public getTreeItem(element: MavenModuleItem): vscode.TreeItem {
        return element;
    }
    
    /**
     * 获取子项
     */
    public async getChildren(element?: MavenModuleItem): Promise<MavenModuleItem[]> {
        if (!element) {
            // 根层级 - 查找所有根POM文件
            return this.findRootModules();
        } else if (element.children) {
            // 返回预先加载的子模块
            return element.children;
        } else {
            // 加载子模块
            return this.loadSubmodules(element.pomPath);
        }
    }
    
    /**
     * 查找工作区中的所有根Maven模块
     */
    private async findRootModules(): Promise<MavenModuleItem[]> {
        const workspaceFolders = vscode.workspace.workspaceFolders;
        if (!workspaceFolders) {
            return [];
        }
        
        const rootModules: MavenModuleItem[] = [];
        
        // 为每个工作区文件夹查找根POM
        for (const folder of workspaceFolders) {
            try {
                const rootPomPath = await this.mavenUtils.findRootPom(folder.uri.fsPath);
                if (rootPomPath) {
                    // 尝试解析POM获取项目名称
                    const projectName = await this.extractProjectName(rootPomPath);
                    const moduleName = projectName || path.basename(path.dirname(rootPomPath));
                    
                    // 加载子模块
                    const submodules = await this.loadSubmodules(rootPomPath);
                    
                    // 创建根模块项
                    const rootModule = new MavenModuleItem(
                        moduleName,
                        rootPomPath,
                        submodules.length > 0 ? 
                            vscode.TreeItemCollapsibleState.Expanded : 
                            vscode.TreeItemCollapsibleState.Collapsed,
                        submodules
                    );
                    
                    rootModules.push(rootModule);
                } else {
                    // 如果找不到根POM，尝试查找文件夹中的所有POM
                    const pomFiles = await vscode.workspace.findFiles(
                        new vscode.RelativePattern(folder, '**/pom.xml'),
                        '**/node_modules/**'
                    );
                    
                    // 仅添加直接位于根目录的POM
                    for (const pomFile of pomFiles) {
                        const modulePath = path.dirname(pomFile.fsPath);
                        if (path.dirname(modulePath) === folder.uri.fsPath) {
                            const projectName = await this.extractProjectName(pomFile.fsPath);
                            const moduleName = projectName || path.basename(modulePath);
                            
                            rootModules.push(new MavenModuleItem(
                                moduleName,
                                pomFile.fsPath,
                                vscode.TreeItemCollapsibleState.None
                            ));
                        }
                    }
                }
            } catch (error) {
                console.error(`加载工作区 ${folder.name} 的Maven模块时出错:`, error);
            }
        }
        
        return rootModules;
    }
    
    /**
     * 从POM文件解析项目名称
     */
    private async extractProjectName(pomPath: string): Promise<string | undefined> {
        try {
            const content = await fs.promises.readFile(pomPath, 'utf8');
            const nameMatch = content.match(/<name>([^<]+)<\/name>/);
            if (nameMatch) {
                return nameMatch[1].trim();
            }
            
            // 如果没有name标签，尝试获取artifactId
            const artifactMatch = content.match(/<artifactId>([^<]+)<\/artifactId>/);
            if (artifactMatch) {
                return artifactMatch[1].trim();
            }
            
            return undefined;
        } catch (error) {
            console.error(`解析POM文件 ${pomPath} 失败:`, error);
            return undefined;
        }
    }
    
    /**
     * 加载POM文件的子模块
     */
    private async loadSubmodules(pomPath: string): Promise<MavenModuleItem[]> {
        try {
            const content = await fs.promises.readFile(pomPath, 'utf8');
            const moduleMatches = content.matchAll(/<module>([^<]+)<\/module>/g);
            const pomDir = path.dirname(pomPath);
            const submodules: MavenModuleItem[] = [];
            
            for (const match of moduleMatches) {
                const moduleName = match[1].trim();
                const modulePomPath = path.join(pomDir, moduleName, 'pom.xml');
                
                if (fs.existsSync(modulePomPath)) {
                    // 递归加载子模块的子模块
                    const projectName = await this.extractProjectName(modulePomPath);
                    const displayName = projectName || moduleName;
                    
                    // 检查是否有更深层次的子模块
                    const hasMoreSubmodules = await this.hasSubmodules(modulePomPath);
                    
                    submodules.push(new MavenModuleItem(
                        displayName,
                        modulePomPath,
                        hasMoreSubmodules ? 
                            vscode.TreeItemCollapsibleState.Collapsed : 
                            vscode.TreeItemCollapsibleState.None
                    ));
                }
            }
            
            return submodules;
        } catch (error) {
            console.error(`加载子模块失败: ${error}`);
            return [];
        }
    }
    
    /**
     * 检查POM是否有子模块
     */
    private async hasSubmodules(pomPath: string): Promise<boolean> {
        try {
            const content = await fs.promises.readFile(pomPath, 'utf8');
            return content.includes('<modules>') && content.includes('<module>');
        } catch {
            return false;
        }
    }
}
